package hh.leecode;

import java.util.Arrays;

/**
 * 翻转链表，单链表 input 1234 output 4321
 */
public class s数据结构_链表_翻转链表1 {


    public static void main(String[] args) {
        Node1 head = new Node1(null, 0);
        Node1 current = head;

        for (Integer e : Arrays.asList(1,2,3,4)) {
            current.next = new Node1(null, e);
            current = current.next;
        }

        Node1 reverse = reverse(head);
        while (reverse != null) {
            System.out.println(reverse.val);
            reverse = reverse.next;
        }
    }

    /**
     * 记住prev 和current
     * 吧他们两当做滑动窗口，每次遍历往前移动一步
     * 当current=null说明没数据了，翻转完毕
     * 此时入参node变为tail，他next引用需要置空
     */
    public static Node1 reverse(Node1 node) {
        if(node==null)return null;
        // 单链表翻转需要记住prev节点
        Node1 prev=node;
        Node1 current=node.next;

        while (current != null) {
            Node1 next = current.next;
            current.next=prev;
            prev = current;
            current = next;
        }
        node.next=null;

        return prev;


    }



    public static class Node1{
        Node1 next;
        Object val;

        public Node1(Node1 next, Object val) {
            this.next = next;
            this.val = val;
        }

        @Override
        public String toString() {
            return "{" +
                    "val=" + val +
                    '}';
        }

        public Node1() {

        }
    }


}






